import threading
import requests
import re
import os
import subprocess
from Loop_exists_file_thread import Loop_exists_file_thread
from tkinter import Text,END
from typing import Optional

def send_cmd(idm_path: str, save_path: str, address: str):
    filename = address.split('#')[-1]
    url = get_download_address(address)
    if url != "":
        cmd = idm_path + " /d "+url+" /f "+filename + " /p "+save_path+" /n"
        subprocess.run(cmd)
        return save_path + "\\" + filename
    return ""


def get_download_address(url: str) -> str:
    """
    从给定的页面URL中提取真实的下载地址

    参数:
        url (str): 包含下载链接的页面URL
        例如:https://fuckingfast.co/omol7vklou0b#File_Name-part01.rar

    返回:
        str: 提取出的真实下载地址，如果提取失败则返回空字符串
    """
    response = requests.get(url)
    if response.status_code == 200:
        pattern = r"window\.open\(\"(http.*)\"\)"
        matches = re.findall(pattern, response.text)
        return matches[0]
    else:
        return ""


class Loop_download_list_thread(threading.Thread):
    def __init__(self,
                 tk,
                 dl_page_list: list,
                 idm_path: str = "C:\\Program Files (x86)\\Internet Download Manager\\IDMan.exe",
                 save_path: str = "C:\\"
                 ):
        """传入下载页面列表,IDM路径,保存路径"""
        super().__init__()
        self._stop_event = threading.Event()
        self.dl_page_list = dl_page_list
        self.dl_address = ""
        self.dl_filename = ""
        self.idm_path = idm_path
        self.save_path = save_path
        self.daemon = True
        self.Loop_exists_file_thread: Optional[Loop_exists_file_thread] = None
        self.tk=tk

    def run(self):
        for dl_page in self.dl_page_list:  # 第一条下载页面
            if self._stop_event.is_set() == True:
                break
            self.dl_filename = dl_page.split('#')[-1]  # 由下载页面获取文件名
            if os.path.exists(self.save_path+"\\"+self.dl_filename):
                break
            self.dl_address = get_download_address(dl_page)  # 取得真实下载地址
            if self.dl_address != "":
                cmd = self.idm_path + " /d "+self.dl_address+" /f " + \
                    self.dl_filename + " /p "+self.save_path+" /n"
                print(cmd)
                try:
                    returncode = subprocess.Popen(cmd).returncode
                    print(returncode)
                    self.Loop_exists_file_thread = Loop_exists_file_thread(self.tk.txt_dl_status,
                        self.save_path+"\\"+self.dl_filename, 10)
                    self.Loop_exists_file_thread.start()
                    self.Loop_exists_file_thread.join()
                except Exception as e:
                    print(e)
                    break
            else:
                print("下载地址错误")
                break
        self.tk.txt_dl_status.insert(END,"全部下载完成\n")
        self.tk.btn_start.config(state="normal")
        self.tk.btn_stop.config(state="disabled")

    def stop(self):
        self._stop_event.set()


if __name__ == "__main__":
    # url = [
    #     "https://fuckingfast.co/tkjdniniyxbi#Hot_Rod_Mayhem_--_fitgirl-repacks.site_--_.part1.rar",
    #     "https://fuckingfast.co/2poyg649g2xd#Hot_Rod_Mayhem_--_fitgirl-repacks.site_--_.part2.rar"
    # ]

    # t = Loop_download_list_thread(url)
    # t.start()
    # t.join()
    ...
